package com.one.service.impl;

import com.one.bean.OrderInfo;
import com.one.bean.Orders;
import com.one.bean.Product;
import com.one.constant.RabbitMQConstant;
import com.one.constant.RequestReturnConstant;
import com.one.mapper.OrderMapper;
import com.one.mapper.ProductMapper;
import com.one.mapper.UserMapper;
import com.one.producer.RabbitMQTopicProducer;
import com.one.service.FlashSaleOrderService;
import com.one.service.ProductService;
import com.one.util.RedisUtils;
import com.one.util.RequestReturn;
import com.one.util.RequestReturnFactory;
import com.one.vo.ProductParamVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Create on 2022-01-17
 * <p>
 * Author: LiangWei
 * <p>
 * Description: 抢购订单接口实现类
 **/
@Service
public class FlashSaleOrderServiceImpl implements FlashSaleOrderService {
    @Autowired
    private ProductService productService;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private RabbitMQTopicProducer rabbitMQTopicProducer;

    @Autowired
    private UserMapper userMapper;

    @Override
    public RequestReturn<String> createFlashSaleTradeOrder(Integer userId,ProductParamVo productParamVo) {
        //只需要判断商品是否符合抢购要求
        if(!productService.judgeProductPurchaseAndStatus(productParamVo.getProdId())){
            //不是抢购商品，返回错误码7001
            return RequestReturnFactory.fail(RequestReturnConstant.NOT_RUSH_PRODUCT_CODE,RequestReturnConstant.NOT_RUSH_PRODUCT_MSG,null);
        }
        if(productParamVo.getProductNum()!=1){
            //传入数量不为1，直接报错，返回错误码7002
            return RequestReturnFactory.fail(RequestReturnConstant.NUM_NOT_ONE_CODE,RequestReturnConstant.NUM_NOT_ONE_MSG,null);
        }
        //生成订单号，准备入redis缓存
        String tradeOrderNo = "T"+ DateTimeFormatter.ofPattern("yyyyMMddHHmmss").format(LocalDateTime.now())+ UUID.randomUUID().toString().substring(0,6);

        //定义一个hashmap集合，存放发送的消息队列中的数据
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("userId",userId);
        paramMap.put("productParamVo",productParamVo);
        paramMap.put("tradeOrderNo",tradeOrderNo);

        rabbitMQTopicProducer.sendTopicMsg2TopicExchange(RabbitMQConstant.RABBITMQ_TOPIC_EXCHANGE,RabbitMQConstant.RABBITMQ_TOPIC_ROUTING_BATCH,paramMap);
        //返回订单号
        return RequestReturnFactory.success(RequestReturnConstant.RETURN_SUCCESS_CODE,RequestReturnConstant.CREATE_ORDER_SUCCESS_MSG,tradeOrderNo);
    }
}
